define(['moment', 'module/system/service/WatchDogService'], function (moment) {
    return ['$state','$scope', '$filter', '$stateParams', 'config', 'MMWService','$mdDialog', '$timeout', '$interval', 'WatchDogService', '$mddProvider',
        function ($state, $scope, $filter, $stateParams, config, $MMWService, $mdDialog, $timeout, $interval, $WatchDogService, $mddProvider) {
            $scope._event = {};
            $scope._fn = {};
        $scope.subOpCondition = {
            plot_no : '',
            op_no : '',
            sub_op_no: '',
            is_check_in: 0  //false / /已到站
        };
        $scope.subOpInfo = {};
        $scope.subOpItem = {};
        $scope.dashboard = {};      //儀錶板物件
        $scope.barcode_info = {

        };

        $scope.init = function(){
            $scope.employeeWorkReason = config.cache.sys_parameter.EmployeeWorkReason;
            $scope.mode = 'setting';
            $scope.dashboard = {
                plotInfo : {
                    templateUrl : 'module/moduleG/program/G01/dashboard/plotInfo.html'
                },
                subOperation : {
                    templateUrl : 'module/moduleG/program/G01/dashboard/subOperation.html'
                }
            };
            $scope.PageConfig = {
                page : 0,
                page_count : 25
            };

            // 讀取查詢條件暫存
            var subOpCondition = localStorage.getItem(config.appName + '_G0101');
            if(subOpCondition){
                subOpCondition = JSON.parse(subOpCondition);
                $scope.subOpCondition = subOpCondition;
            }

            // 讀取dashboard暫存
            if (typeof(Storage) !== 'undefined') {
                var panel_setting = JSON.parse(localStorage.getItem(config.appName + '_G0101_panel'));
                if(panel_setting){
                    $scope.dashboardPanel = panel_setting;
                }
            }

            // 外部傳入條件後自動查詢
            if($stateParams.data){
                if($stateParams.data.plot_no && $stateParams.data.op_no){
                    $scope.subOpCondition.plot_no = $stateParams.data.plot_no;
                    $scope.subOpCondition.op_no = $stateParams.data.op_no;
                    $scope.subOpCondition.op_name = $stateParams.data.op_name;
                    $scope.subOpCondition.is_check_in = 1;
                    $scope._fn['G0101_confirm'].click();
                }
            }

            //20180828 add by Dustdusk for Android 時不顯示小鍵盤
            if(window.cordova){
                document.getElementById('input_plot').readOnly = true;
            }

        };


        //$scope.back = function(){
        //    $scope.disconnection = false;
        //    $scope.final(function(){
        //        $scope.$root.changeProgram('home', true);
        //    });
        //};

        $scope.final = function(callback){
            if(refresh_timer != undefined){
                $timeout.cancel(refresh_timer);
                refresh_timer = undefined;
            }
            $WatchDogService.stopWatch();
            if(typeof callback === 'function')
                callback();
        };

        $scope.search = function(){
            $WatchDogService.startWatch(dog, true);
        };

            $scope._fn['G0101_confirm'] = {
                click: () => {
                    if ($scope.subOpCondition.op_no != '') {
                        applySetting(function () {
                            // 20230322 modify by 文蔚 for M#131021 泡泡選單子作業跳轉子作業工作平台報錯
                            setTimeout(function () {
                                $scope.changeForm('G0101_Detail');
                            }, 100);
                        });
                    } else {
                        $scope.$root.showAlert($filter('translate')('G0101.msg.condition_not_enough'));
                    }
                }
            }

            var backSubOpCondition;
            $scope._fn['G0101_Detail_setting'] = {
                click: () => {
                    backSubOpCondition = angular.copy($scope.subOpCondition);
                    //20181018 add by Dustdusk for M#:
                    $scope.disconnection = false;
                    if (refresh_timer != undefined) {
                        $timeout.cancel(refresh_timer);
                        refresh_timer = undefined;
                    }
                    $WatchDogService.stopWatch();
                    $mdDialog.serviceDialog('G0102Service', {
                        parent: 'G0101',
                        subOpCondition: angular.copy($scope.subOpCondition),
                        callback: function (dialog) {
                            $scope.subOpCondition = dialog.subOpCondition;
                            applySetting(function () {
                                dialog.hide();
                            });
                        },
                        close: function () {
                            $scope.subOpCondition = backSubOpCondition;
                            $WatchDogService.startWatch(dog);
                        }
                    });
                }
            }

        //查詢 - 作業站開窗
        $scope._event['G0101_op_no'] = {
            click: () => {
                $scope.$root.showQueryList({
                    pageRecord: 25,
                    header: [
                        { label: $filter('translate')('common.queryList.op_c'), code: 'page_no' },
                        { label: $filter('translate')('common.queryList.op_n'), code: 'page_name' }
                    ],
                    query: function (conditions, feedback) {
                        $MMWService.pageNumberInfoGet(
                            {
                                form_name: 'PageNo_31',
                                query_condition_info: [
                                    { column_name: 'MASTERNO', query_mode: '0', value: config.setting.OperatingArea, merge_condition_model: 'AND' }
                                ]
                            }, function (data) {
                                var temp = $filter('filter')(data, { favourite: '1' });
                                //var temp = data.page_number_info_get;
                                if (temp && temp.length) {
                                    feedback(temp);
                                } else {
                                    $scope.$root.showConfirm($filter('translate')('G0101.msg.favorite_empty'), function (confirmDialog) {
                                        confirmDialog.hide();
                                        $timeout(function () {
                                            $scope.favorite(function () {
                                                $scope._event['G0101_op_no'].click();
                                            });
                                        }, 200);
                                    });
                                }
                            }
                        );
                    },
                    selectCode: $scope.subOpCondition.op_no || '',
                    confirm: function (selectItem, dialog) {
                        $scope.subOpCondition.op_no = selectItem.page_no;
                        $scope.subOpCondition.op_name = selectItem.page_name;
                        dialog.hide();
                    }
                });
            }
        }

        //查詢 - 生產批複合開窗
            $scope._event['G0101_plot_no'] = {
                click: () => {
                    if ($scope.subOpCondition.op_no != '') {
                        var _options = {
                            form_name: '',
                            condition: [],
                            pageRecord: 25,
                            header: [
                                { label: $filter('translate')('common.queryList.plot_no'), code: 'page_no' },
                                { label: $filter('translate')('G0101.queryList.cur_qty'), code: 'cur_qty' }
                            ],
                            selectCode: $scope.subOpCondition.plot_no,
                            setCondition: function (conditions) {
                                conditions.push({ column_name: 'OPNo', query_mode: '2', value: $scope.subOpCondition.op_no });
                                return conditions;
                            },
                            confirm: function (selectItem) {
                                $scope.subOpCondition.plot_no = selectItem.page_no;
                                $scope._fn['G0101_confirm'].click();
                            }
                        };
                        if ($scope.subOpCondition.is_check_in==0) {
                            _options.form_name = 'PageNo_28';
                            _options.condition.push({ name: $filter('translate')('common.queryList.plot_no'), column_name: 'LotNo', query_mode: '2', value: $scope.subOpCondition.plot_no });
                        } else {
                            _options.form_name = 'PageNo_29';
                            _options.condition.push({ name: $filter('translate')('common.queryList.plot_no'), column_name: 'ds.LotNo', query_mode: '2', value: $scope.subOpCondition.plot_no });
                        }
                        $MMWService.showQueryListPNIG(_options);
                    }
                    else {
                        $scope.$root.showAlert($filter('translate')('G0101.msg.op_no_empty'));
                    }
                }
            }

            $scope.input_sub_op_no = function (sub_op_no){
                $scope.subOperationFilter = sub_op_no;
            };

        //載入設定
            function applySetting(callback, work_log, type) {
            var content = {
                plot_no : $scope.subOpCondition.plot_no || '',
                op_no : $scope.subOpCondition.op_no || '',
                sub_op_no: '',
                is_check_in: ($scope.subOpCondition.is_check_in==1) ? 'Y' : 'N'
            };
            if(type == 'work_log'){
                content.plot_no = work_log.plot_no;
                content.op_no = work_log.op_no;
            } 
            subOpInfoGet(content, function(data){
                $scope.subOpInfo = data;
                localStorage.setItem(config.appName + '_G0101', JSON.stringify($scope.subOpCondition));
                $scope.mode = '';
                $WatchDogService.startWatch(dog);
                if(callback)
                    callback();
            }, true);
        }

        //20181018 modify by Dustdusk for M#: 一般錯誤時使用alert，背景更新時改用confrim
        var refresh_timer;
        function ErrorHandler(msg, isShowLoading, callback){
            if($scope){
                $scope.$root.showAlert(msg);
                if(!isShowLoading){
                    $scope.disconnection = true;
                    $scope.refresh =  function(){
                        $scope.disconnection = false;
                        $timeout.cancel(refresh_timer);
                        refresh_timer = undefined;
                        callback();
                    };
                    if(refresh_timer == undefined){
                        refresh_timer = $timeout(function(){
                            $scope.refresh();
                        }, config.setting.RefreshTime*1000);
                    }
                }
            }
        }

        //子作業參數檢查
        function subOpParametersCheckProcess(content, callback){
            $MMWService.sendToServer({
                uri: 'ServicesSTD.Module_WIP.sub_op_parameters_check_process',
                content: content,
                success: function (data) {
                    if (callback)
                        callback();
                }
            });
        }

        function subOpInfoGetBark(feedback, isShowLoading){
            var content = {
                plot_no : $scope.subOpCondition.plot_no || '',
                op_no : $scope.subOpCondition.op_no || '',
                sub_op_no: '',
                is_check_in: ($scope.subOpCondition.is_check_in==1) ? 'Y' : 'N'
            };
            subOpInfoGet(content, feedback, isShowLoading);
        }

        //取得目前生產批的子作業
        function subOpInfoGet(content, feedback, isShowLoading){
            $MMWService.sendToServer({
                uri: 'ServicesSTD.Module_WIP.sub_op_info_get',
                content: content,
                success: function (data) {
                    if(feedback){
                        feedback(data);
                    }
                },
                error: function(data){
                    //20170331 modify by Dustdusk for 當失敗時，isShowLoading為false則重新執行一次
                    //20181018 modify by Dustdusk for M#: 一般錯誤時使用alert，背景更新時改用confrim
                    ErrorHandler(data.Message, isShowLoading, function(){
                        subOpInfoGet(content, feedback, isShowLoading);
                    });
                },
                netError: function(msg){
                    //20170331 modify by Dustdusk for 當失敗時，isShowLoading為false則重新執行一次
                    //20181018 modify by Dustdusk for M#: 一般錯誤時使用alert，背景更新時改用confrim
                    ErrorHandler(msg, isShowLoading, function(){
                        subOpInfoGet(content, feedback, isShowLoading);
                    });
                }
            }, isShowLoading);
        }

        var dog = {
            bark: function(feed, next){
                subOpInfoGetBark(function(data){
                    $scope.subOpInfo = data;
                    next();
                    // wipPlotStatusInfoGet(next, next == undefined);
                }, next == undefined);
            }
        };
/****Dashboard**************************************************************************************************************************************/
        $scope.dashboardPanel = ['plotInfo', 'subOperation'];
        $scope.isInnerContentHide = false;

        $scope.togglePanel = function(sectionName, $event){
            var target = $scope.dashboard[sectionName];
            if(sectionName == 'workMaterial' || sectionName == 'workMaterialOp' || sectionName == 'productInfo' || sectionName == 'accessory'){
                $scope.isInnerContentHide = !$scope.isInnerContentHide;
            } else {
                target.isContentHide = !target.isContentHide;
            }
        };
            $scope._fn['G0101_favorite'] = {
                click: () => {
                    $scope.favorite();
                }
            }
            $scope._fn['G0101_Detail_favorite'] = {
                click: () => {
                    $scope.favorite();
                }
            }
        $scope.favorite = function(callback){
            if(config.setting.OperatingArea==''){
                $scope.$root.showAlert($filter('translate')('home.showAlert'));
                return;
            }
            $MMWService.showQueryListPNIG({
                form_name: 'PageNo_31',
                mode:'M',
                key:'page_no',
                header : [
                    {label: $filter('translate')('common.queryList.op_c'), code:'page_no'},
                    {label: $filter('translate')('common.queryList.op_n'), code:'page_name'}
                ],
                selectKey:{key:'favourite', true:'1', false:'0'},
                setCondition:function(conditions){
                    conditions.push({column_name:'MASTERNO', query_mode:'0', value:config.setting.OperatingArea, merge_condition_model:'AND' });
                    return conditions;
                },
                confirm: function(selectItem, dialog){
                    var content = {
                        master_type: 6, //6.子作業工作平台,
                        master_no: config.setting.OperatingArea,
                        favourite_sub_op_detail:[]
                    };
                    if(selectItem && selectItem.length > 0){
                        selectItem.forEach(function(item){
                            if(item.favourite == '1'){
                                content.favourite_sub_op_detail.push({
                                    op_no: item.page_no,
                                    op_name: item.page_name
                                });
                            }
                        });
                    }
                    beforeSaveFavorite(content.favourite_sub_op_detail, function(){
                        $MMWService.sendToServer({
                            uri: 'ServicesSTD.Module_SYS.favourite_machine_process',
                            content : content,
                            success : function(data){
                                dialog.hide();
                                if(callback)
                                    callback();
                            }
                        });
                    });
                }
            });
        };

        function beforeSaveFavorite(favoriteList, callback){
            var isDeleteCurrentOp = false;
            if($scope.subOpCondition.op_no && $scope.subOpCondition.op_no != ''){
                if(favoriteList && favoriteList.length > 0){
                    var filterList = $filter('filter')(favoriteList, {op_no: $scope.subOpCondition.op_no}, true);
                    if(filterList.length == 0){
                        isDeleteCurrentOp = true; //使用者將"目前的作業站"從我的最愛移除了
                    }
                }
            }

            if($scope.mode != 'setting'){
                if(isDeleteCurrentOp){
                    //從我的最愛移除了目前的作業站，回到作業站選擇頁面
                    $scope.$root.showAlert($filter('translate')('G0101.msg.favorite_remove'),function(){
                        $scope.final(function(){
                            $scope.subOpCondition.op_no = '';
                            $scope.subOpCondition.op_name = '';
                            $scope.mode = 'setting';
                            if(callback)
                                callback();
                        });
                    });
                }else{
                    if(callback)
                        callback();
                }
            }else{
                if(isDeleteCurrentOp){
                    $scope.subOpCondition.op_no = '';
                    $scope.subOpCondition.op_name = '';
                }
                if(callback)
                    callback();
            }
        }

        $scope.changePanel = function(event, panelCode){
            event.stopPropagation();
            var panelList = [
                {panelCode : 'workMaterial', panelName: $filter('translate')('dashboard.workMaterial.title')},
                {panelCode : 'productInfo', panelName: $filter('translate')('dashboard.productInfo.title')},
                {panelCode : 'accessory', panelName: $filter('translate')('dashboard.accessory.title')}
            ];
            if($scope.feedingOpionOn){
                panelList.push({panelCode : 'workMaterialOp', panelName: $filter('translate')('dashboard.workMaterialOp.title')});
            }

            //$scope.dashboardPanel = ['plotInfo','machineStatusPlus','workMaterial','productInfo', 'subOperation'];
            $scope.$root.showSelect({
                title : $filter('translate')('common.msg.plz_select'),
                label : 'panelName',
                code : 'panelCode',
                selectCode : panelCode,
                list : panelList,
                confirm : function(item, dialog){
                    var now_panel_index = $scope.dashboardPanel.indexOf(panelCode);
                    var select_panel_index = $scope.dashboardPanel.indexOf(item.panelCode);
                    //當為-1時表示選擇的不再列表內，則不用做交換
                    if(select_panel_index != -1){
                        $scope.dashboardPanel[select_panel_index] = panelCode;
                    }
                    $scope.dashboardPanel[now_panel_index] = item.panelCode;
                    localStorage.setItem(config.appName + '_G0101_panel', JSON.stringify($scope.dashboardPanel));
                    dialog.hide();
                }
            });

        };

/**************************************************************************************************************************************************/
        var element_plot_no;
        //20170511 modify by Dustdusk for 新增barcode/QRcode輸入功能
        $scope.focusInputPlot = function(){
            element_plot_no = document.getElementById('input_plot');
            element_plot_no.focus();
        };

        //barcode輸入
        $scope.input_plot_no = function(barcode){
            input_plot_no_callback(barcode);
        };

            //QRCode輸入
            $scope._event['G0101_work_log'] = {
                click: () => {
                    $scope.$root.OpenScanner({
                        after: function (result) {
                            input_plot_no_callback(result.text);
                        },
                        exception: function () {
                            //目前裝置無法使用相機
                            $scope.$root.showAlert($filter('translate')('common.msg.cant_use_camera'));
                        },
                        orientation: 'landscape'
                    });
                }
            }

        function input_plot_no_callback(barcode){
            //檢查輸入的對不對
            var barcode_plot_no = barcode;
            var temp_plot_array = barcode_plot_no.split(';');
            if(temp_plot_array.length == 2){
                // 20200421 modify by WeiTing for M#70174 - 生產任務改成不用刷子作業站(sub_op_no)。 
                var content = {
                    plot_no : temp_plot_array[0] || '',
                    op_no : temp_plot_array[1] || ''
                };
                // 20200427 modify by WeiTing for M#70174 - 修正刷入條碼後，要賦予值到 subOpCondition.plot_no 和 subOpCondition.op_no。
                $scope.subOpCondition.plot_no = temp_plot_array[0];
                $scope.subOpCondition.op_no = temp_plot_array[1];

                applySetting(function(){}, content, 'work_log');
            } else {
                $scope.$root.showAlert($filter('translate')('G0101.msg.barcode_format_error'), function(){
                    element_plot_no.focus();
                });
            }
        }

        $scope.getPages = function(list, PageConfig, filterItem){
            if(list){
                var temp_list = list.filter(function(item, index, array){
                    var isOK = true,
                        keys = Object.keys(filterItem);
                    for(var i =0; i<keys.length;i++){
                        var key = keys[i];
                        if(isOK && item[key]!=null && filterItem[key] && filterItem[key]!=''){
                            if(item[key].indexOf(filterItem[key]) == -1){
                                isOK = false;
                                break;
                            }
                        }
                    }
                    //狀態過濾
                    if(isOK && $scope.dashboard['subOperation'].statusList.indexOf(item.status) ==-1){
                        isOK = false;
                    }
                    return isOK;
                });
                if(PageConfig){
                    PageConfig.total_page = Math.ceil(temp_list.length/PageConfig.page_count)||1;
                    if(PageConfig.page >= PageConfig.total_page){
                        PageConfig.page = 0;
                    }
                    var index = PageConfig.page*PageConfig.page_count;
                    return temp_list.slice(index, index+PageConfig.page_count);
                } else {
                    return temp_list;
                }
            } else {
                return list;
            }
        };

        $scope.clickSubOpItem = function(item){
            $WatchDogService.stopWatch();
            $mdDialog.serviceDialog('G0103Service',{
                pdline_no: $scope.subOpInfo.pdline_no,
                op_no: $scope.subOpInfo.op_no,
                plot_no: $scope.subOpInfo.plot_no,
                cur_qty: $scope.subOpInfo.cur_qty,
                subOpItem: item,
                callback: function(feedback, dialog){
                    //20191120 modify by Dustdusk for M#: 修正人員查詢後自動更新畫面
                    if($scope.mode != 'setting'){
                        var content = {
                            plot_no : $scope.subOpCondition.plot_no || '',
                            op_no : $scope.subOpCondition.op_no || '',
                            sub_op_no: item.sub_op_no,
                            is_check_in: ($scope.subOpCondition.is_check_in==1) ? 'Y' : 'N'
                        };
                        subOpInfoGet(content, function(data){
                            dialog.pdline_no = data.pdline_no;
                            dialog.op_no = data.op_no;
                            dialog.plot_no = data.plot_no;
                            dialog.cur_qty = data.cur_qty;
                            if(data.sub_op_detail && data.sub_op_detail.length > 0){
                                dialog.subOpItem = data.sub_op_detail[0];
                            }
                            if (feedback)
                                feedback();
                        }, false);
                    }
                },
                close: function(){
                    if($scope.mode != 'setting'){
                        $WatchDogService.startWatch(dog);
                    }
                }
            });
        };
    }
];});
